/**
 * 
 */
package edu.rit.cs.web.panels;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponentLabel;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.StatelessForm;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.PropertyModel;

import edu.rit.cs.core.pojos.AUser;

/**
 * @author Abhishek Shrestha (axs1430)
 * @author Juan Saldana (jjs6109)
 * @author Victor Alvarez (vxa1557)
 */
public abstract class LoginPanel extends Panel {
  private static final long serialVersionUID = 1L;

  private String username;
  private String password;

  protected abstract AUser getUserByName(String username);

  protected abstract void hide();

  public LoginPanel(final String id) {
    super(id);
    add(new FeedbackPanel("feedback"));
    
    Form<Void> form = new StatelessForm<Void>("loginForm") {
      private static final long serialVersionUID = 1L;
      
      @Override
      protected void onSubmit() {
        AUser user = getUserByName(username);

        if (user == null) {
          error("Invalid username!");

        } else {
          if (DigestUtils.shaHex(password).equals(user.getPassword())) {
            hide();
          } else {
            info("login failed");
          }
        }
      }
    };
    TextField<String> textField = new RequiredTextField<String>("username",
        new PropertyModel<String>(this, "username"));

    form.add(textField);
    form.add(new FormComponentLabel("usernameLbl", textField));

    TextField<String> passwField = new PasswordTextField("password",
        new PropertyModel<String>(this, "password"));
    passwField.setRequired(true);
    form.add(passwField);
    form.add(new FormComponentLabel("passwordLbl", passwField));

    add(form);
  }
}
